<template>
  <div class="login">
    <div class="load">
      <!-- 头像 -->
      <div class="avatar">
        <img src="../assets/rose.jpg" alt="" />
      </div>
      <!-- 登录 -->
      <el-form :model="lognForm" :rules="loginRules" ref="loginRef">
        <el-form-item prop="username">
          <el-input
            v-model="lognForm.username"
            prefix-icon="iconfont icon-user"
          ></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input
            v-model="lognForm.password"
            prefix-icon="iconfont icon-3702mima"
          ></el-input>
        </el-form-item>
        <div class="btn">
          <el-button type="primary" @click="userLoad">登录</el-button>
          <el-button type="info" @click="clearFrom">重置</el-button>
        </div>
      </el-form>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 表单数据
      lognForm: {
        username: 'admin',
        password: '123456'
      },
      // 表单数据验证规则
      loginRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 4, max: 16, message: '长度在 6 到 16 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 4, max: 16, message: '长度在 4 到 16 个字符', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    // 登录功能
    userLoad() {
      // 预校验
      this.$refs.loginRef.validate(async val => {
        if (val) {
          const { data: res } = await this.$http.post('login', this.lognForm)
          if (res.meta.status !== 200) {
            return this.$message.error(res.meta.msg)
          }
          this.$message.success(res.meta.msg)
          window.sessionStorage.setItem('token', res.data.token)
          this.$router.push('/home')
        }
      })
    },
    // 清空表单
    clearFrom() {
      this.$refs.loginRef.resetFields()
    }
  }
}
</script>

<style lang="less" scoped>
.login {
  height: 100%;
  background-color: #2b4b6b;
}

.load {
  position: absolute;
  width: 450px;
  height: 305px;
  background-color: #fff;
  border-radius: 5px;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

.avatar {
  position: absolute;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 130px;
  height: 130px;
  border: 1px solid #eee;
  border-radius: 50%;
  padding: 7px;
  box-shadow: 0 0 10px #eee;
  background-color: #fff;
  img {
    width: 100%;
    height: 100%;
    border-radius: 50%;
  }
}

.el-form {
  position: absolute;
  bottom: 0;
  width: 100%;
  padding: 20px;
  box-sizing: border-box;
}

.btn {
  text-align: right;
}
</style>
